﻿using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using kysec.RAL.EFToMySql;
using System.Xml;
using System.Xml.Linq;

namespace kysec.Bll.News
{
    /// <summary>
    /// 搜索相关资讯
    /// </summary>
    public class Search
    {
        /// <summary>
        /// 搜索初级新闻，用于在前台网页中显示
        /// </summary>
        /// <param name="type">新闻类别，0：行业新闻，1：公司新闻</param>
        /// <param name="takeitem">每页显示的条数</param>
        /// <param name="page">页码</param>
        /// <returns>返回找的信息</returns>
        public static List<newData> getFirstNews(int type,int takeitem,int page)
        {
            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity() // 从Cache中读取信息
               .RetrieveObject(string.Format("GetFirstInfo_{0}_{1}_{2}"
                , type, page, takeitem));
            if (o == null)
            {
                MySql_kysecContectionString ctx = new MySql_kysecContectionString();
                try
                {
                    var list = (from c in ctx.tb_news
                                where c.c_i_classify == type && c.c_b_isDelete == false
                                orderby c.c_dt_publishDate descending
                                select new
                                {
                                    id = c.c_uq_newId,
                                    publishDate = c.c_dt_publishDate,
                                    title = c.c_vc_title
                                })
                               .Skip(page * takeitem)

                               .Take(takeitem)

                               .ToList();

                    #region 将信息放入Cahce中
                    if (list.Any())
                    {

                        var packlist = list.Select(c => new newData()
                        {
                            newsId = c.id,
                            publishDate = c.publishDate,
                            title = c.title
                        }).ToList();
                        kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity()
                            .AddObjectWithAbsoluteTime(string.Format("GetFirstInfo_{0}_{1}_{2}", type, page, takeitem)
                            , packlist,
                            600000
                            , System.Web.Caching.CacheItemPriority.Normal);
                        return packlist;
                    }
                }
                catch (Exception ex)
                {
                    string error=ex.ToString()+ "\t查询第一级新闻信息时出错";
                    kysec.CR.Logger.MyLogger.Error(typeof(Search),error);
                }
                finally {
                    ctx.Dispose();
                }
                #endregion

                return new List<newData>();
            }
            return (List<newData>)o;
        }

        /// <summary>
        /// 找到详细的新闻，用于在后台操作时显示
        /// </summary>
        /// <param name="type">新闻类别，0：行业新闻，1：公司新闻</param>
        /// <param name="takeitem">每页显示的条数</param>
        /// <param name="page">页码</param>
        /// <returns>返回找的信息</returns>
        public static List<tb_news> getDetailNews(int type, int takeitem, int page)
        {
            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity() // 从Cache中读取信息
               .RetrieveObject(string.Format("GetDetailInfo_{0}_{1}_{2}"
                , type, page, takeitem));
            if (o == null)
            {
                MySql_kysecContectionString ctx = new MySql_kysecContectionString();
                try
                {
                    var list = (from c in ctx.tb_news
                                where c.c_i_classify == type && c.c_b_isDelete == false
                                orderby c.c_dt_publishDate descending
                                select new
                                {
                                    id = c.c_uq_newId,
                                    imgpath = c.c_x_imgPath,
                                    title = c.c_vc_title,
                                    publish = c.c_dt_publishDate,
                                    fromAdd = c.c_nvc_from,
                                    type = c.c_i_classify,
                                    content = c.c_ntx_content,
                                    isDel = c.c_b_isDelete
                                })
                               .Skip(page * takeitem)

                               .Take(takeitem)

                               .ToList();

                    #region 将信息放入Cahce中
                    if (list.Any())
                    {
                        var packlist = list.Select(c => new tb_news()
                        {
                            c_uq_newId = c.id,
                            c_dt_publishDate = c.publish,
                            c_vc_title = c.title,
                            c_x_imgPath = c.imgpath,
                            c_nvc_from = c.fromAdd,
                            c_i_classify = c.type,
                            c_ntx_content = c.content,
                            c_b_isDelete = c.isDel
                        }).ToList();
                        kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity()
                            .AddObjectWithAbsoluteTime(string.Format("GetDetailInfo_{0}_{1}_{2}", type, page, takeitem)
                            , list,
                            600000
                            , System.Web.Caching.CacheItemPriority.Normal);
                        return packlist;
                    }
                }
                catch (Exception ex)
                {
                    string error = ex.ToString() + "\t查询详细新闻时出错";
                    kysec.CR.Logger.MyLogger.Error(typeof(Search), error);
                }
                finally
                {
                    ctx.Dispose();
                }
                #endregion

                return new List<tb_news>();
            }
            return (List<tb_news>)o;
        }

        /// <summary>
        /// 查询某一条具体的新闻信息，用于用户的操作
        /// </summary>
        /// <param name="newId">新闻ID</param>
        /// <param name="type">新闻类型0：行业新闻，1：公司新闻</param>
        /// <param name="takeitem">每页显示的条数</param>
        /// <param name="page">页码</param>
        /// <returns>返回找的信息</returns>
        public static List<tb_news> getNewsInfo(string id,int type)
        {
            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity() // 从Cache中读取信息
               .RetrieveObject(string.Format("GetNewsInfo_{0}_{1}",id
                , type));
            if (o == null)
            {
                MySql_kysecContectionString ctx = new MySql_kysecContectionString();
                Guid newId = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(id));
                id = newId.ToString();
                try
                {
                    var list = ctx.tb_news.Where(c => c.c_i_classify == type && c.c_b_isDelete == false &&c.c_uq_newId.Equals(id))
                               .ToList();

                    #region 将信息放入Cahce中
                    if (list.Any())
                    {
                        kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity()
                            .AddObjectWithAbsoluteTime(string.Format("GetNewsInfo_{0}_{1}",newId, type)
                            , list,
                            600000
                            , System.Web.Caching.CacheItemPriority.Normal);
                        return list;
                    }
                }
                catch (Exception ex)
                {
                    string error = ex.ToString() + "\t查询具体的某一条新闻时出错";
                    kysec.CR.Logger.MyLogger.Error(typeof(Search), error);
                }
                finally
                {
                    ctx.Dispose();
                }
                    #endregion

                return new List<tb_news>();
            }
            return (List<tb_news>)o;
        }

        /// <summary>
        /// 得到某一类型的新闻显示在前台中的滚动图片
        /// </summary>
        /// <param name="type">新闻类型0：行业新闻，1：公司新闻</param>
        /// <param name="takeitem">每页显示的条数</param>
        /// <param name="page">页码</param>
        /// <returns>返回找的信息</returns>
        public static List<newsImgData> getNewsImg(int type,int takeitem,int page)
        {
            var o = kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity() // 从Cache中读取信息
                          .RetrieveObject(string.Format("GetNewsImg_{0}"
                           , type+DateTime.Now.Second));
            if (o == null)
            {
                MySql_kysecContectionString ctx = new MySql_kysecContectionString();
                try
                {
                    var list = (from c in ctx.tb_news
                                where c.c_i_classify == type && c.c_b_isDelete == false
                                orderby c.c_dt_publishDate descending
                                select new
                                {
                                    id = c.c_uq_newId,                                   
                                    imgpath = c.c_x_imgPath,
                                    title=c.c_vc_title
                                })
                               .Skip(page * takeitem)

                               .Take(takeitem)

                               .ToList();

                    #region 将信息放入Cahce中
                    if (list.Any())
                    {

                        var packlist = list.Select(c => new newsImgData()
                        {
                            newsId = c.id,
                            imgUrl= new XElement(c.imgpath) ,
                            title =c.title
                        }).ToList();
                        kysec.CR.Cache.CacheManage.DefaultStrategy.GetEntity()
                            .AddObjectWithAbsoluteTime(string.Format("GetNewsImg_{0}", type + DateTime.Now.Second)
                            , packlist,
                            600000
                            , System.Web.Caching.CacheItemPriority.Normal);
                        return packlist;
                    }
                }
                catch (Exception ex)
                {
                    string error = ex.ToString() + "\t查询图片新闻信息时出错";
                    kysec.CR.Logger.MyLogger.Error(typeof(Search), error);
                }
                finally
                {
                    ctx.Dispose();
                }
                    #endregion

                return new List<newsImgData>();
            }
            return (List<newsImgData>)o;
        }
    }

    /// <summary>
    /// news操作类
    /// </summary>
    public class news
    {
        /// <summary>
        /// 插入新闻信息，返回成功信息
        /// </summary>
        /// <param name="model">数据集</param>
        /// <returns>0：添加失败 1：添加成功 2：添加异常</returns>
        public static string AddNews(tb_news model)
        {
            string result = "0";

            Guid id = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(HttpContext.Current.Session["userId"].ToString()));
            MySql_kysecContectionString ctx = new MySql_kysecContectionString();

            XElement xe = kysec.CR.Common.GetImgFromFCK.GetHtmlImageUrlXml(model.c_ntx_content, 1);//将html文件中的图片转换为xml格式存储
            try
            {
                tb_news news = new tb_news {
                    c_uq_userId = id.ToString(),
                    c_uq_newId = Guid.NewGuid().ToString(),
                    c_vc_title = model.c_vc_title,
                    c_ntx_content = model.c_ntx_content,
                    c_i_classify = model.c_i_classify,
                    c_dt_publishDate = DateTime.Now,
                    c_nvc_from = model.c_nvc_from,
                    c_x_imgPath = xe.ToString(),
                    c_i_hot = 0,
                    c_b_isDelete = false
                };
                ctx.AddObject("tb_news", news);
                result = ctx.SaveChanges().ToString();
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t插入信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(news), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 修改新闻信息
        /// </summary>
        /// <param name="newsId">需要修改的新闻的id</param>
        /// <param name="model">数据集</param>
        /// <returns>0：信息不存在或修改失败 1：修改成功 2：修改异常</returns>
        public static string UpdateNews(string id, tb_news model)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            Guid newId = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(id));
            id = newId.ToString();
            try
            {
                var list = ctx.tb_news.Where(c => c.c_uq_newId.Equals(id) && c.c_b_isDelete == false).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        item.c_vc_title = model.c_vc_title;
                        item.c_ntx_content = model.c_ntx_content;
                        item.c_nvc_from = model.c_nvc_from;
                        item.c_i_hot = model.c_i_hot;
                        item.c_i_classify = model.c_i_classify;
                        item.c_dt_publishDate = DateTime.Now;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t修改信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(news), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 删除新闻信息，可以同时恢复删除的新闻
        /// </summary>
        /// <param name="newsId">需要删除的新闻信息的Id</param>
        /// <returns>0：没有找到信息或删除失败 1：删除成功 2：删除异常</returns>
        public static string DeleteNews(string id)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            Guid newsId = Guid.Parse(kysec.CR.Common.EncodeByBase64.Decode(id));
            id = newsId.ToString();
            try
            {
                var list = ctx.tb_news.Where(c => c.c_uq_newId.Equals(id)).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        if (item.c_b_isDelete)
                            item.c_b_isDelete = false;
                        else
                            item.c_b_isDelete = true;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t删除信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(news), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 设置是否为热点信息，若信息为热点则可以设置为普通，否则依然
        /// </summary>
        /// <param name="newsId">需要改变的新闻的id</param>
        /// <returns>0：信息没有找到或者失败 1：设置成功 2：设置异常</returns>
        public static string SetHotNews(Guid newsId)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            string id = newsId.ToString();
            try
            {
                var list = ctx.tb_news.Where(c => c.c_uq_newId.Equals(id) && c.c_b_isDelete == false).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        if (item.c_i_hot == 0)
                            item.c_i_hot = 1;
                        else
                            item.c_i_hot = 0;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t设置是否为热点信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(news), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }

        /// <summary>
        /// 设置新闻的类型，若为公司新闻可以改变为行业新闻，否则依然
        /// </summary>
        /// <param name="newsId">需要设置的新闻</param>
        /// <returns>0：没有找到信息或者操作失败 1：更改成功 2：更改异常</returns>
        public static string SetTypeNews(Guid newsId)
        {
            string result = "0";

            MySql_kysecContectionString ctx = new MySql_kysecContectionString();
            string id = newsId.ToString();

            try
            {
                var list = ctx.tb_news.Where(c => c.c_uq_newId.Equals(id) && c.c_b_isDelete == false).ToList();

                if (list.Count == 0)
                    result = "0";
                else
                {
                    foreach (var item in list)
                    {
                        if (item.c_i_classify == 0)
                            item.c_i_classify = 1;
                        else
                            item.c_i_classify = 0;
                    }
                    result = ctx.SaveChanges().ToString();
                }
            }
            catch (Exception ex)
            {
                string error = ex.ToString() + "\t设置新闻类型信息时出错";
                kysec.CR.Logger.MyLogger.Error(typeof(news), error);
                result = "2";
            }
            finally { ctx.Dispose(); }
            return result;
        }
    }
}
